package com.francis.springbootcommonutil.number;



import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.regex.Pattern;

/**
 * <p>Title: NumberUtil</p>
 * <p>Description: NumberUtil double四舍五入，数字格式转换，前面补零，纯数字字符串判断</p>
 * <p>Copyright: ChenWei Copyright(c) 2018/p>
 * @author  ChenWei
 * @version 0.0.1
 * <pre>Histroy:
 *       2020/6/22 16:09 Create by ChenWei
 *</pre>
*/
public class NumberUtil {


	public static void main(String[] args) {
		//format double to 0.00
		Double d = 2.33222233;
		System.out.println(format(d,"0.00"));
		Long l = 1111L;
		System.out.println(format(l,"0L"));
		System.out.println(format(l,"00000000"));
		// 前面补零
		Integer i = 44;
		System.out.println(format(i, "000000"));
	}


	/**
	 * @methodName round
	 * @description 四舍五入处理.
	 * @param v, scale
	 * @return double
	 * @author ChenWei
	 * @date 2020/6/22 16:34
	 */
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b =  BigDecimal.valueOf(v);
		return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * @methodName round
	 * @description 提供精确的小数位四舍五入处理..
	 * @param v, scale
	 * @return double
	 * @author ChenWei
	 * @date 2020/6/22 16:34
	 */
	public static String doubleToStr(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b =  BigDecimal.valueOf(v);
		return b.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
	}



	public static String format(Double v, String pattern) {
		if (v == null) {
			v = 0.0;
		}
		try {
			return new DecimalFormat(pattern).format(v);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return v.toString();
	}

	public static String format(Long v, String pattern) {
		if (v == null) {
			v = 0L;
		}
		try {
			return new DecimalFormat(pattern).format(v);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return v.toString();
	}

	public static String format(Integer v, String pattern) {
		if (v == null) {
			v = 0;
		}
		try {
			return new DecimalFormat(pattern).format(v);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return v.toString();
	}


	private static String  NumberUtils_REGX_CONSTANT = "^-?\\d+(\\.\\d+)?$";
	/**
	 * @methodName isNumber
	 * @description 判断一个字符串是否是纯数字
	 * @param number
	 * @return boolean
	 * @author ChenWei
	 * @date 2020/6/22 16:32
	 */
	public static boolean isNumber(String number){
		Pattern pattern = Pattern.compile(NumberUtils_REGX_CONSTANT);
		if (number == null){
			return Boolean.FALSE;
		}
		return pattern.matcher(number).matches();
	}


}
